package club.smartdot.sort;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import club.smartdot.util.RedisUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Tuple;

public class RedisSortSet {
	public static void main(String[] args) {
		JedisPool pool = RedisUtil.open("127.0.0.1", 6379);
		Jedis jedis = null;
		try {
			// 从连接池中获取Jedis对象
			jedis = pool.getResource();
			String key = "salary";
			jedis.zadd(key, 2000D, "John");
			// 使用方法:zadd(String key, Map<String, Double>)添加多个数据
			Map<String, Double> map = new HashMap<>();
			map.put("Tom", 3500D);
			map.put("Marry", 6500D);
			map.put("Rose", 3600D);
			map.put("Mike", 5060D);
			// 添加多个数据
			jedis.zadd(key, map);
			// 查询返回全部的数据，没有score
			Set<String> zrangeByScore3 = jedis.zrangeByScore(key, "-inf", "+inf");
			Set<String> zrangeByScore2 = zrangeByScore3;
			Set<String> zrangeByScore = zrangeByScore2;
			Set<String> sets = zrangeByScore;
			Iterator<String> iterator = sets.iterator();
			while(iterator.hasNext()) {
				System.out.println("排序小-大的成员" + iterator.next());
			}
			
			// 带有score的数据
			Set<Tuple> tuple = jedis.zrangeByScoreWithScores(key, "-inf", "+inf");
			Iterator<Tuple> iters = tuple.iterator();
			while(iters.hasNext()) {
				Tuple tu = iters.next();
				System.out.println("排序小-大的成员:" + tu.getElement() + "# score:" + tu.getScore());
			}
			System.out.println("有序集合成员数据量:" + jedis.zcard(key));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				// 使用完的连接池对象，放回连接池
				jedis.close();
			}
		}
	}
}
